package com.rssreader.playtts;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.newsvoice.activity.DashBoardActivity;
import com.newsvoice.activity.NewsVoiceApplication;
import com.newsvoice.activity.R;
import com.newsvoice.activity.ICallbackHandler;
import com.newsvoice.activity.SearchByTagActivity;
import com.newsvoice.activity.WebService;
import com.newsvoice.activity.WebViewActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.method.ScrollingMovementMethod;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.ShareActionProvider;
import android.widget.TextView;

public class ShowExtractedArticle extends DashBoardActivity implements
		ICallbackHandler, OnPreparedListener {
	private TextView textView;
	private final Handler handler = new Handler();
	private ShareActionProvider mShareActionProvider;
	private TTS tts;

	private Button buttonRead;
	private TextView textStreamed;
	private ImageButton buttonPlayAndPause;

	private String titleArticle;
	private String urlArticle;
	private String textArticle;

	private ExtractedArticle extractedArticle = null;
	// private StreamingMediaPlayer mediaPlayer;
	private StreamingMediaPlayer audioStreamer;
	private LinearLayout tagsLayout;
	private TextView fullPageLink;
	private SeekBar seekBarProgress;
	private int mediaFileLengthInMilliseconds; // this value contains the song
												// duration in milliseconds.
												// Look at getDuration() method
												// in MediaPlayer class

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_extracted_article);
		setHeader(getIntent().getStringExtra("title"), true, true, false, true);
		textStreamed = (TextView) findViewById(R.id.text_kb_streamed);
		textView = (TextView) findViewById(R.id.textView1);
		buttonRead = (Button) findViewById(R.id.button_stream);
		buttonPlayAndPause = (ImageButton) findViewById(R.id.button_play);
		tagsLayout = (LinearLayout) findViewById(R.id.tags);
		fullPageLink = (TextView) findViewById(R.id.full_page_label);

		titleArticle = getIntent().getStringExtra("title");
		urlArticle = getIntent().getStringExtra("urlString");

		buttonPlayAndPause.setEnabled(false);

		fullPageLink.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getApplicationContext(),
						WebViewActivity.class);
				intent.putExtra("url", urlArticle);
				intent.putExtra("title", titleArticle);
				startActivity(intent);
			}
		});

		// initView();
		buttonPlayAndPause.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// if (mediaPlayer.getMp().isPlaying()) {
				// mediaPlayer.getMp().pause();
				// buttonPlayAndPause.setImageResource(R.drawable.button_play);
				// } else {
				// mediaPlayer.getMp().start();
				// buttonPlayAndPause
				// .setImageResource(R.drawable.button_pause);
				// }
				if (audioStreamer.getMediaPlayer().isPlaying()) {
					audioStreamer.getMediaPlayer().pause();
					buttonPlayAndPause.setImageResource(R.drawable.button_play);
				} else {
					audioStreamer.getMediaPlayer().start();
					audioStreamer.startPlayProgressUpdater();
					buttonPlayAndPause
							.setImageResource(R.drawable.button_pause);
				}
				// isPlaying = !isPlaying;

			}
		});
		textView.setMovementMethod(new ScrollingMovementMethod());
		buttonRead.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// startStreamingAudio();

				final SeekBar seekBar = (SeekBar) findViewById(R.id.seek_bar);

				tts = new TTS(getApplicationContext(), textStreamed,
						buttonPlayAndPause, buttonRead, seekBar, handler);

				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							tts.startMediaStream(textArticle);
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}).start();
				buttonRead.setEnabled(false);
				buttonPlayAndPause.setEnabled(true);

				// new Runnable() {
				//
				// @Override
				// public void run() {
				// // TODO Auto-generated method stub
				// TTS tts = new TTS();
				// try {
				// tts.startMediaStream(getApplicationContext(), textArticle);
				// } catch (MalformedURLException e) {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// } catch (IOException e) {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// } catch (JSONException e) {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// }
				// }
				// }.run();

				// try {
				// startStreaming(getApplicationContext(), textArticle,
				// 5028, 216);
				// } catch (IOException e) {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// }
			}
		});

		SharedPreferences setting = getSharedPreferences(
				NewsVoiceApplication.filePrefrences, MODE_PRIVATE);
		Map<String, String> params = new HashMap<String, String>();
		System.out.println(setting.getString("id", "noid"));
		params.put("url", urlArticle);
		params.put("id", setting.getString("id", "noid"));
		callWebService(params);

	}

	// private void initView() {
	// buttonPlayAndPause = (ImageButton) findViewById(R.id.button_play);
	// buttonPlayAndPause.setOnClickListener(this);
	//
	// seekBarProgress = (SeekBar) findViewById(R.id.seek_bar);
	// seekBarProgress.setMax(99); // It means 100% .0-99
	// seekBarProgress.setOnTouchListener(this);
	//
	// mediaPlayer = new MediaPlayer();
	// mediaPlayer.setOnBufferingUpdateListener(this);
	// mediaPlayer.setOnCompletionListener(this);
	// }

	@Override
	public void response(String response) {
		// TODO Auto-generated method stub
		// Log.d("callMethod", response);
		System.out.println(response);
		System.out.println();
		try {
			JSONObject jso = new JSONObject(response);
			textArticle = jso.getString("text");
			// String urlString = jso.getString("url");
			// URL url = new URL(urlString);
			// System.out.println(url);
			// List<String> sentences = new ArrayList<String>();
			// JSONArray array = jso.getJSONArray("sentences");
			// StringBuilder sb = new StringBuilder();
			// for (int i = 0; i < array.length(); i++) {
			// String tmp = array.getString(i);
			// sb.append(tmp);
			// sentences.add(tmp);
			// System.out.println(tmp);
			// }
			// extractedArticle = new ExtractedArticle();
			// extractedArticle.setSentences(sentences);
			// extractedArticle.setUrl(url);
			textView.setText(textArticle);
			String[] tags;
			JSONArray jsonTags = jso.getJSONArray("tags");
			tags = new String[jsonTags.length()];
			for (int i = 0; i < jsonTags.length(); i++) {
				tags[i] = jsonTags.get(i).toString();
				System.out.println("tag : " + tags[i]);
			}

			View[] views = new View[tags.length];
			for (int i = 0; i < tags.length; i++) {
				final String text = tags[i];
				SpannableString content = new SpannableString(text);
				content.setSpan(new UnderlineSpan(), 0, text.length(), 0);
				TextView textView = new TextView(getApplicationContext());
				textView.setText(content);
				textView.setTextColor(getResources().getColor(
						R.color.link_color));
				textView.setPadding(5, 0, 5, 0);
				views[i] = textView;
				textView.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(getApplicationContext(),
								SearchByTagActivity.class);
						intent.putExtra("tag", text);
						startActivity(intent);
					}
				});
			}

			populateText(tagsLayout, views, getApplicationContext());
			// mediaPlayer = new StreamingMediaPlayer(
			// extractedArticle.getSentences(), this);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// } catch (MalformedURLException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
		}

	}

	private void callWebService(Map<String, String> params) {
		WebService webService = new WebService(
				"http://192.168.5.1:8080/VoiceNewsServer/rest/services/",
				"extractedarticle", params, this, WebService.GET_METHOD, this);
		webService.execute();
	}

	private void startStreamingAudio() {
		try {
			final SeekBar seekBar = (SeekBar) findViewById(R.id.seek_bar);
			if (audioStreamer != null) {
				audioStreamer.interrupt();
			}
			audioStreamer = new StreamingMediaPlayer(this, textStreamed,
					buttonPlayAndPause, buttonRead, seekBar);
			// audioStreamer
			// .startStreaming(
			// "http://www.pocketjourney.com/downloads/pj/tutorials/audio.mp3",
			// 1717, 214);

			audioStreamer.startStreaming(textArticle, 5208, 216);
			buttonRead.setEnabled(false);
			buttonPlayAndPause.setEnabled(true);
		} catch (IOException e) {
			Log.e(getClass().getName(), "Error starting to stream audio.", e);
		}

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		System.out.println("onpause showarticle");
		super.onPause();
		if (audioStreamer != null) {
			MediaPlayer tmp = audioStreamer.getMediaPlayer();
			if (tmp != null && tmp.isPlaying()) {
				tmp.pause();
				// tmp.release();
				// tmp = null;
			}

		}

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		System.out.println("ondestroy showextrac");

		if (tts != null) {
			MediaPlayer mp = tts.getMediaPlayer();
			if (mp != null && mp.isPlaying()) {
				mp.pause();
			}
		}

	}

	private void populateText(LinearLayout ll, View[] views, Context mContext) {
		Display display = getWindowManager().getDefaultDisplay();
		ll.removeAllViews();
		int maxWidth = display.getWidth() - 20;

		LinearLayout.LayoutParams params;
		LinearLayout newLL = new LinearLayout(mContext);
		newLL.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		newLL.setGravity(Gravity.LEFT);
		newLL.setOrientation(LinearLayout.HORIZONTAL);

		int widthSoFar = 0;

		for (int i = 0; i < views.length; i++) {
			LinearLayout LL = new LinearLayout(mContext);
			LL.setOrientation(LinearLayout.HORIZONTAL);
			LL.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
			LL.setLayoutParams(new ListView.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			// my old code
			// TV = new TextView(mContext);
			// TV.setText(textArray[i]);
			// TV.setTextSize(size); <<<< SET TEXT SIZE
			// TV.measure(0, 0);
			views[i].measure(0, 0);
			params = new LinearLayout.LayoutParams(views[i].getMeasuredWidth(),
					LayoutParams.WRAP_CONTENT);
			// params.setMargins(5, 0, 5, 0); // YOU CAN USE THIS
			// LL.addView(TV, params);
			LL.addView(views[i], params);
			LL.measure(0, 0);
			widthSoFar += views[i].getMeasuredWidth();// YOU MAY NEED TO ADD THE
														// MARGINS
			if (widthSoFar >= maxWidth) {
				ll.addView(newLL);

				newLL = new LinearLayout(mContext);
				newLL.setLayoutParams(new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
				newLL.setOrientation(LinearLayout.HORIZONTAL);
				newLL.setGravity(Gravity.LEFT);
				params = new LinearLayout.LayoutParams(LL.getMeasuredWidth(),
						LL.getMeasuredHeight());
				newLL.addView(LL, params);
				widthSoFar = LL.getMeasuredWidth();
			} else {
				newLL.addView(LL);
			}
		}
		ll.addView(newLL);
	}

	// /**
	// * Method which updates the SeekBar primary progress by current song
	// playing
	// * position
	// */
	// private void primarySeekBarProgressUpdater() {
	// seekBarProgress.setProgress((int) (((float) mediaPlayer
	// .getCurrentPosition() / mediaFileLengthInMilliseconds) * 100)); // This
	// // math
	// // construction
	// // give
	// // a
	// // percentage
	// // of
	// // "was playing"/"song length"
	// if (mediaPlayer.isPlaying()) {
	// Runnable notification = new Runnable() {
	// public void run() {
	// primarySeekBarProgressUpdater();
	// }
	// };
	// handler.postDelayed(notification, 1000);
	// }
	// }
	//
	// @Override
	// public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
	// // TODO Auto-generated method stub
	// seekBarProgress.setSecondaryProgress(arg1);
	//
	// }
	//
	// @Override
	// public void onCompletion(MediaPlayer arg0) {
	// // TODO Auto-generated method stub
	// /**
	// * MediaPlayer onCompletion event handler. Method which calls then song
	// * playing is complete
	// */
	// buttonPlayAndPause.setImageResource(R.drawable.button_play);
	// }
	//
	// @Override
	// public boolean onTouch(View v, MotionEvent arg1) {
	// // TODO Auto-generated method stub
	// if (v.getId() == R.id.seek_bar) {
	// /**
	// * Seekbar onTouch event handler. Method which seeks MediaPlayer to
	// * seekBar primary progress position
	// */
	// if (mediaPlayer.isPlaying()) {
	// SeekBar sb = (SeekBar) v;
	// int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100)
	// * sb.getProgress();
	// mediaPlayer.seekTo(playPositionInMillisecconds);
	// }
	// }
	// return false;
	// }
	//
	// @Override
	// public void onClick(View v) {
	// // TODO Auto-generated method stub
	// if (v.getId() == R.id.button_play) {
	// /**
	// * ImageButton onClick event handler. Method which start/pause
	// * mediaplayer playing
	// */
	// try {
	// mediaPlayer
	// .setDataSource("http://localhost/TTSService/Service/service.svc/TTS?voiceIndex=1&rate=0&extension=ogg&text="
	// + textView.getText().toString()
	// .replace(" ", "%20")); // setup song
	// // from
	// // http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3
	// // URL to
	// // mediaplayer
	// // data source
	// mediaPlayer.prepare(); // you must call this method after setup
	// // the datasource in setDataSource
	// // method. After calling prepare() the
	// // instance of MediaPlayer starts load
	// // data from URL to internal buffer.
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	//
	// mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets
	// // the
	// // song
	// // length
	// // in
	// // milliseconds
	// // from
	// // URL
	//
	// if (!mediaPlayer.isPlaying()) {
	// mediaPlayer.start();
	// buttonPlayAndPause.setImageResource(R.drawable.button_pause);
	// } else {
	// mediaPlayer.pause();
	// buttonPlayAndPause.setImageResource(R.drawable.button_play);
	// }
	//
	// primarySeekBarProgressUpdater();
	// }
	//
	// }

	/** Returns a share intent */
	private Intent getDefaultShareIntent() {
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_SUBJECT, "SUBJECT");
		intent.putExtra(Intent.EXTRA_TEXT, "Extra Text");
		return intent;
	}

	@Override
	public void btnShareClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_TEXT, urlArticle + "\n" + titleArticle);
		intent.putExtra(Intent.EXTRA_TITLE, titleArticle);
		intent.putExtra(android.content.Intent.EXTRA_SUBJECT, titleArticle);
		startActivity(Intent.createChooser(intent, "Share"));

	}

	public void startStreaming(final Context context, final String text,
			long mediaLengthInKb, long mediaLengthInSeconds) throws IOException {
		Runnable r = new Runnable() {
			public void run() {
				try {
					downloadAudioIncrement(context, text);
				} catch (IOException e) {
					Log.e(getClass().getName(),
							"Unable to initialize the MediaPlayer for fileUrl="
									+ text, e);
					return;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		new Thread(r).start();
	}

	/**
	 * Download the url stream to a temporary location and then call the
	 * setDataSource for that local file
	 * 
	 * @throws JSONException
	 */
	public void downloadAudioIncrement(Context context, String text)
			throws IOException, JSONException {
		// String mediaUrl =
		// "http://192.168.5.1:8080/VoiceNewsServer/rest/ttsservices/audio";
		String sentence = text.substring(0, 100);
		String urlString = "http://translate.google.com.vn/translate_tts?ie=UTF-8&q="
				+ sentence.replace(" ", "%20") + "&tl=vi";
		URL urlTTS = new URL(urlString);
		URLConnection cn = urlTTS.openConnection();
		System.out.println(cn.getURL().toString());
		cn.addRequestProperty("User-Agent",
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
		cn.setConnectTimeout(20000);
		// cn.setRequestProperty("Content-Type", "application/json");
		//
		// ((HttpURLConnection) cn).setRequestMethod("POST");
		// cn.setDoOutput(true);
		// // cn.setDoInput(true);
		// JSONObject data = new JSONObject();
		// data.put("data", text);
		// OutputStreamWriter wr = new OutputStreamWriter(cn.getOutputStream());
		// wr.write(data.toString());
		// wr.close();

		cn.connect();
		// cn.getContent();
		InputStream stream = cn.getInputStream();

		File downloadingMediaFile = new File(context.getCacheDir(),
				"downloadingMedia.dat");

		// Just in case a prior deletion failed because our code crashed or
		// something, we also delete any previously
		// downloaded file to ensure we start fresh. If you use this code,
		// always delete
		// no longer used downloads else you'll quickly fill up your hard disk
		// memory. Of course, you can also
		// store any previously downloaded file in a separate data cache for
		// instant replay if you wanted as well.
		if (downloadingMediaFile.exists()) {
			downloadingMediaFile.delete();
		}

		FileOutputStream out = new FileOutputStream(downloadingMediaFile);
		byte buf[] = new byte[16384];
		int totalBytesRead = 0, incrementalBytesRead = 0;
		do {
			int numread = stream.read(buf);
			if (numread <= 0)
				break;
			out.write(buf, 0, numread);
			totalBytesRead += numread;
			incrementalBytesRead += numread;
			System.out.println(totalBytesRead);
		} while (true);
		stream.close();
		out.close();
		FileInputStream fis = new FileInputStream(downloadingMediaFile);

		MediaPlayer m = new MediaPlayer();
		m.setDataSource(fis.getFD());
		// m.setDataSource(downloadingMediaFile.getPath());
		m.setOnPreparedListener(this);
		m.prepareAsync();
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		// TODO Auto-generated method stub
		mp.start();
	}

}
